notebooks/community/migration/UJ6 legacy AutoML Natural Language Text Classification.ipynb (1,691 lines of code) (raw):
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "8edU8FN2lH6o"
},
"outputs": [],
"source": [
"# Copyright 2021 Google LLC\n",
"#\n",
"# Licensed under the Apache License, Version 2.0 (the \"License\");\n",
"# you may not use this file except in compliance with the License.\n",
"# You may obtain a copy of the License at\n",
"#\n",
"# https://www.apache.org/licenses/LICENSE-2.0\n",
"#\n",
"# Unless required by applicable law or agreed to in writing, software\n",
"# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
"# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
"# See the License for the specific language governing permissions and\n",
"# limitations under the License."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "text_title:migration,automl,icn"
},
"source": [
"# AutoML natural language text classification model\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "JE-aKjayJjkF"
},
"source": [
"## Installation\n",
"\n",
"Install the latest version of AutoML SDK."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "7dxB6-B0JjkG"
},
"outputs": [],
"source": [
"! pip3 install google-cloud-automl"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "Iddo-8HmJjkH"
},
"source": [
"Install the Google *cloud-storage* library as well."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "xHvi6EFSJjkH"
},
"outputs": [],
"source": [
"! pip3 install google-cloud-storage"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "ktRTgB8DJjkI"
},
"source": [
"### Restart the Kernel\n",
"\n",
"Once you've installed the AutoML SDK and Google *cloud-storage*, you need to restart the notebook kernel so it can find the packages."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "x1g4mBdlJjkI"
},
"outputs": [],
"source": [
"import os\n",
"\n",
"if not os.getenv(\"AUTORUN\"):\n",
" # Automatically restart kernel after installs\n",
" import IPython\n",
"\n",
" app = IPython.Application.instance()\n",
" app.kernel.do_shutdown(True)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "Af0jTPSgl9yh"
},
"source": [
"## Before you begin\r\n",
"\r\n",
"### GPU run-time\r\n",
"\r\n",
"*Make sure you're running this notebook in a GPU runtime if you have that option. In Colab, select* **Runtime > Change Runtime Type > GPU**\r\n",
"\r\n",
"### Set up your GCP project\r\n",
"\r\n",
"**The following steps are required, regardless of your notebook environment.**\r\n",
"\r\n",
"1. [Select or create a GCP project](https://console.cloud.google.com/cloud-resource-manager). When you first create an account, you get a $300 free credit towards your compute/storage costs.\r\n",
"\r\n",
"2. [Make sure that billing is enabled for your project.](https://cloud.google.com/billing/docs/how-to/modify-project)\r\n",
"\r\n",
"3. [Enable the AutoML APIs and Compute Engine APIs.](https://console.cloud.google.com/flows/enableapi?apiid=ml.googleapis.com,compute_component)\r\n",
"\r\n",
"4. [Google Cloud SDK](https://cloud.google.com/sdk) is already installed in AutoML Notebooks.\r\n",
"\r\n",
"5. Enter your project ID in the cell below. Then run the cell to make sure the\r\n",
"Cloud SDK uses the right project for all the commands in this notebook.\r\n",
"\r\n",
"**Note**: Jupyter runs lines prefixed with `!` as shell commands, and it interpolates Python variables prefixed with `$` into these commands."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "hceMthWGJjkI"
},
"source": [
"#### Project ID\n",
"\n",
"**If you don't know your project ID**, try to get your project ID using `gcloud` command by executing the second cell below."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "set_project_id"
},
"outputs": [],
"source": [
"PROJECT_ID = \"[your-project-id]\" # @param {type:\"string\"}"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "Xzde8OBYDdh2"
},
"outputs": [],
"source": [
"if PROJECT_ID == \"\" or PROJECT_ID is None or PROJECT_ID == \"[your-project-id]\":\n",
" # Get your GCP project id from gcloud\n",
" shell_output = !gcloud config list --format 'value(core.project)' 2>/dev/null\n",
" PROJECT_ID = shell_output[0]\n",
" print(\"Project ID:\", PROJECT_ID)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "0UfsdLCEJjkJ"
},
"outputs": [],
"source": [
"! gcloud config set project $PROJECT_ID"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "jT0fijejJjkK"
},
"source": [
"#### Region\n",
"\n",
"You can also change the `REGION` variable, which is used for operations\n",
"throughout the rest of this notebook. Below are regions supported for AutoML. We recommend when possible, to choose the region closest to you.\n",
"\n",
"- Americas: `us-central1`\n",
"- Europe: `europe-west4`\n",
"- Asia Pacific: `asia-east1`\n",
"\n",
"You cannot use a Multi-Regional Storage bucket for training with AutoML. Not all regions provide support for all AutoML services. For the latest support per region, see [Region support for AutoML services]()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "CTBlncfrJjkK"
},
"outputs": [],
"source": [
"REGION = \"us-central1\" # @param {type: \"string\"}"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "J_croPBoJjkK"
},
"source": [
"#### Timestamp\n",
"\n",
"If you are in a live tutorial session, you might be using a shared test account or project. To avoid name collisions between users on resources created, you create a timestamp for each instance session, and append onto the name of resources which will be created in this tutorial."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "KKxStk5bJjkL"
},
"outputs": [],
"source": [
"from datetime import datetime\n",
"\n",
"TIMESTAMP = datetime.now().strftime(\"%Y%m%d%H%M%S\")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "h_L3MRsOmYED"
},
"source": [
"### Authenticate your GCP account\r\n",
"\r\n",
"**If you are using AutoML Notebooks**, your environment is already\r\n",
"authenticated. Skip this step.\r\n",
"\r\n",
"*Note: If you are on an AutoML notebook and run the cell, the cell knows to skip executing the authentication steps.*"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "HvxYUdIfGAM-"
},
"outputs": [],
"source": [
"import os\n",
"import sys\n",
"\n",
"# If you are running this notebook in Colab, run this cell and follow the\n",
"# instructions to authenticate your Google Cloud account. This provides access\n",
"# to your Cloud Storage bucket and lets you submit training jobs and prediction\n",
"# requests.\n",
"\n",
"# If on Vertex, then don't execute this code\n",
"if not os.path.exists(\"/opt/deeplearning/metadata/env_version\"):\n",
" if \"google.colab\" in sys.modules:\n",
" from google.colab import auth as google_auth\n",
"\n",
" google_auth.authenticate_user()\n",
"\n",
" # If you are running this tutorial in a notebook locally, replace the string\n",
" # below with the path to your service account key and run this cell to\n",
" # authenticate your Google Cloud account.\n",
" else:\n",
" %env GOOGLE_APPLICATION_CREDENTIALS your_path_to_credentials.json\n",
"\n",
" # Log in to your account on Google Cloud\n",
" ! gcloud auth login"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "MDUAZaN3JjkL"
},
"source": [
"### Create a Cloud Storage bucket\n",
"\n",
"**The following steps are required, regardless of your notebook environment.**\n",
"\n",
"This tutorial is designed to use training data that is in a public Cloud Storage bucket and a local Cloud Storage bucket for your batch predictions. You may alternatively use your own training data that you have stored in a local Cloud Storage bucket.\n",
"\n",
"Set the name of your Cloud Storage bucket below. It must be unique across all Cloud Storage buckets. "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "bucket"
},
"outputs": [],
"source": [
"BUCKET_NAME = \"[your-bucket-name]\" # @param {type:\"string\"}"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "autoset_bucket"
},
"outputs": [],
"source": [
"if BUCKET_NAME == \"\" or BUCKET_NAME is None or BUCKET_NAME == \"[your-bucket-name]\":\n",
" BUCKET_NAME = PROJECT_ID + \"aip-\" + TIMESTAMP"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "yU6VuylGJjkM"
},
"source": [
"**Only if your bucket doesn't already exist**: Run the following cell to create your Cloud Storage bucket."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "QVRixM4oJjkM"
},
"outputs": [],
"source": [
"! gsutil mb -l $REGION gs://$BUCKET_NAME"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "Mi-Pdh6QJjkN"
},
"source": [
"Finally, validate access to your Cloud Storage bucket by examining its contents:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "aqDptKpYJjkN"
},
"outputs": [],
"source": [
"! gsutil ls -al gs://$BUCKET_NAME"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "fR9geV9pJjkO"
},
"source": [
"### Set up variables\n",
"\n",
"Next, set up some variables used throughout the tutorial.\n",
"### Import libraries and define constants"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "hIHTX-pkJjkO"
},
"source": [
"#### Import AutoML SDK\n",
"\n",
"Import the AutoM SDK into our Python environment."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "qrSkIKVgJjkO"
},
"outputs": [],
"source": [
"import json\n",
"import time\n",
"\n",
"from google.cloud import automl\n",
"from google.protobuf.json_format import MessageToJson"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "lbv411XjJjkP"
},
"source": [
"#### AutoML constants\n",
"\n",
"Setup up the following constants for AutoML:\n",
"\n",
"- `PARENT`: The AutoM location root path for dataset, model and endpoint resources."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "Gx8Eos8PJjkP"
},
"outputs": [],
"source": [
"# AutoM location root path for your dataset, model and endpoint resources\n",
"PARENT = \"projects/\" + PROJECT_ID + \"/locations/\" + REGION"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "JeM1smVJlH61"
},
"source": [
"## Clients\n",
"\n",
"The AutoML SDK works as a client/server model. On your side (the Python script) you will create a client that sends requests and receives responses from the server (AutoML).\n",
"\n",
"You will use several clients in this tutorial, so set them all up upfront.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "c3sR3OxmxXiR"
},
"outputs": [],
"source": [
"def automl_client():\n",
" return automl.AutoMlClient()\n",
"\n",
"\n",
"def prediction_client():\n",
" return automl.PredictionServiceClient()\n",
"\n",
"\n",
"def operations_client():\n",
" return automl.AutoMlClient()._transport.operations_client\n",
"\n",
"\n",
"clients = {}\n",
"clients[\"automl\"] = automl_client()\n",
"clients[\"prediction\"] = prediction_client()\n",
"clients[\"operations\"] = operations_client()\n",
"\n",
"for client in clients.items():\n",
" print(client)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "import_file:flowers,csv,icn"
},
"outputs": [],
"source": [
"IMPORT_FILE = \"gs://cloud-ml-data/NL-classification/happiness.csv\""
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "cjhb6UrAaGwi"
},
"outputs": [],
"source": [
"! gsutil cat $IMPORT_FILE | head -n 10"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "gpsfIXYeaGwj"
},
"source": [
"*Example output*:\n",
"```\n",
"I went on a successful date with someone I felt sympathy and connection with.,affection\n",
"I was happy when my son got 90% marks in his examination,affection\n",
"I went to the gym this morning and did yoga.,exercise\n",
"We had a serious talk with some friends of ours who have been flaky lately. They understood and we had a good evening hanging out.,bonding\n",
"I went with grandchildren to butterfly display at Crohn Conservatory,affection\n",
"I meditated last night.,leisure\n",
"\"I made a new recipe for peasant bread, and it came out spectacular!\",achievement\n",
"I got gift from my elder brother which was really surprising me,affection\n",
"YESTERDAY MY MOMS BIRTHDAY SO I ENJOYED,enjoy_the_moment\n",
"Watching cupcake wars with my three teen children,affection\n",
"```\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "text_create_dataset:migration"
},
"source": [
"## Create a dataset"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "text_datasets_create:migration,old"
},
"source": [
"### [projects.locations.datasets.create](https://cloud.google.com/automl/docs/reference/rest/v1beta1/projects.locations.datasets/create)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "ozaMOwdNJjkT"
},
"source": [
"#### Request"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "IFEbAUNwlH64"
},
"outputs": [],
"source": [
"dataset = {\n",
" \"display_name\": \"happiness_\" + TIMESTAMP,\n",
" \"text_classification_dataset_metadata\": {\"classification_type\": \"MULTICLASS\"},\n",
"}\n",
"\n",
"print(\n",
" MessageToJson(\n",
" automl.CreateDatasetRequest(parent=PARENT, dataset=dataset).__dict__[\"_pb\"]\n",
" )\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "endpoints_undeploymodel:migration,new,response"
},
"source": [
"*Example output*:\n",
"```\n",
"{\n",
" \"parent\": \"projects/migration-ucaip-training/locations/us-central1\",\n",
" \"dataset\": {\n",
" \"displayName\": \"happiness_20210228224317\",\n",
" \"textClassificationDatasetMetadata\": {\n",
" \"classificationType\": \"MULTICLASS\"\n",
" }\n",
" }\n",
"}\n",
"```\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "vHkuSZxkJjkT"
},
"source": [
"#### Call"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "o_JsNpQ1lH65"
},
"outputs": [],
"source": [
"request = clients[\"automl\"].create_dataset(parent=PARENT, dataset=dataset)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "FLqkZMD2JjkT"
},
"source": [
"#### Response"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "5eOgT5MllH65"
},
"outputs": [],
"source": [
"result = request.result()\n",
"\n",
"print(MessageToJson(result.__dict__[\"_pb\"]))"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "PGuI5t-gaGwm"
},
"source": [
"*Example output*:\n",
"```\n",
"{\n",
" \"name\": \"projects/116273516712/locations/us-central1/datasets/TCN2705019056410329088\"\n",
"}\n",
"```\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "wKsCzHBMaGwn"
},
"outputs": [],
"source": [
"# The full unique ID for the dataset\n",
"dataset_id = result.name\n",
"# The short numeric ID for the dataset\n",
"dataset_short_id = dataset_id.split(\"/\")[-1]\n",
"\n",
"print(dataset_id)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "text_datasets_importdata:migration,old"
},
"source": [
"### [projects.locations.datasets.importData](https://cloud.google.com/automl/docs/reference/rest/v1beta1/projects.locations.datasets/importData)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "VkfdNI66lH66"
},
"source": [
"#### Request"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "MtS0VtlMlH66"
},
"outputs": [],
"source": [
"input_config = {\"gcs_source\": {\"input_uris\": [IMPORT_FILE]}}\n",
"\n",
"print(\n",
" MessageToJson(\n",
" automl.ImportDataRequest(name=dataset_id, input_config=input_config).__dict__[\n",
" \"_pb\"\n",
" ]\n",
" )\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "Z52Bxts7aGwo"
},
"source": [
"*Example output*:\n",
"```\n",
"{\n",
" \"name\": \"projects/116273516712/locations/us-central1/datasets/TCN2705019056410329088\",\n",
" \"inputConfig\": {\n",
" \"gcsSource\": {\n",
" \"inputUris\": [\n",
" \"gs://cloud-ml-data/NL-classification/happiness.csv\"\n",
" ]\n",
" }\n",
" }\n",
"}\n",
"```\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "Gmg3fbX_lH66"
},
"source": [
"#### Call"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "yvEILSOelH66"
},
"outputs": [],
"source": [
"request = clients[\"automl\"].import_data(name=dataset_id, input_config=input_config)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "WMUN_7EclH67"
},
"source": [
"#### Response"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "Tf4Yf6JAlH67"
},
"outputs": [],
"source": [
"result = request.result()\n",
"\n",
"print(MessageToJson(result))"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "6Pwgc1IYaGwq"
},
"source": [
"*Example output*:\n",
"```\n",
"{}\n",
"```\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "text_create_and_deploy_model:migration"
},
"source": [
"## Train a model"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "text_models_create:migration,old"
},
"source": [
"### [projects.locations.models.create](https://cloud.google.com/automl/docs/reference/rest/v1beta1/projects.locations.models/create)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "sbJ0wIRHlH67"
},
"source": [
"#### Request"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "mCAqrD7elH68"
},
"outputs": [],
"source": [
"model = automl.Model(\n",
" display_name=\"happiness_\" + TIMESTAMP,\n",
" dataset_id=dataset_short_id,\n",
" text_classification_model_metadata=automl.TextClassificationModelMetadata(),\n",
")\n",
"\n",
"print(\n",
" MessageToJson(automl.CreateModelRequest(parent=PARENT, model=model).__dict__[\"_pb\"])\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "PLAe7LgtaGwr"
},
"source": [
"*Example output*:\n",
"```\n",
"{\n",
" \"parent\": \"projects/migration-ucaip-training/locations/us-central1\",\n",
" \"model\": {\n",
" \"displayName\": \"happiness_20210228224317\",\n",
" \"datasetId\": \"TCN2705019056410329088\",\n",
" \"textClassificationModelMetadata\": {}\n",
" }\n",
"}\n",
"```\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "K2UcVNlAlH68"
},
"source": [
"#### Call"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "FpSHTRfElH69"
},
"outputs": [],
"source": [
"request = clients[\"automl\"].create_model(parent=PARENT, model=model)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "rTFtnIKZlH6-"
},
"source": [
"#### Response"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "UmoMM7VSlH6-"
},
"outputs": [],
"source": [
"result = request.result()\n",
"\n",
"print(MessageToJson(result.__dict__[\"_pb\"]))"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "EzKxl38qaGws"
},
"source": [
"*Example output*:\n",
"```\n",
"{\n",
" \"name\": \"projects/116273516712/locations/us-central1/models/TCN5333697920992542720\"\n",
"}\n",
"```\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "4QxYMtjYaGws"
},
"outputs": [],
"source": [
"# The full unique ID for the training pipeline\n",
"model_id = result.name\n",
"# The short numeric ID for the training pipeline\n",
"model_short_id = model_id.split(\"/\")[-1]\n",
"\n",
"print(model_short_id)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "text_evaluate_the_model:migration"
},
"source": [
"## Evaluate the model"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "yfufMwAEJjkX"
},
"source": [
"### [projects.locations.models.modelEvaluations.list](https://cloud.google.com/automl/docs/reference/rest/v1beta1/projects.locations.models.modelEvaluations/list)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "4wJgA2D8lH6_"
},
"source": [
"#### Call"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "fxMsWaailH6_"
},
"outputs": [],
"source": [
"request = clients[\"automl\"].list_model_evaluations(parent=model_id, filter=\"\")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "IBOLi2gflH6_"
},
"source": [
"#### Response"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "E5xVerw2aGwu"
},
"outputs": [],
"source": [
"evaluations_list = [\n",
" json.loads(MessageToJson(me.__dict__[\"_pb\"])) for me in request.model_evaluation\n",
"]\n",
"\n",
"print(json.dumps(evaluations_list, indent=2))\n",
"# The evaluation slice\n",
"evaluation_slice = request.model_evaluation[0].name"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "bB3px5SBxXig"
},
"source": [
"*Example output*:\n",
"```\n",
"[\n",
" {\n",
" \"name\": \"projects/116273516712/locations/us-central1/models/TCN5333697920992542720/modelEvaluations/1436745357261371663\",\n",
" \"annotationSpecId\": \"3130761503557287936\",\n",
" \"createTime\": \"2021-03-01T02:56:28.878044Z\",\n",
" \"evaluatedExampleCount\": 1193,\n",
" \"classificationEvaluationMetrics\": {\n",
" \"auPrc\": 0.99065405,\n",
" \"confidenceMetricsEntry\": [\n",
" {\n",
" \"recall\": 1.0,\n",
" \"precision\": 0.01424979,\n",
" \"f1Score\": 0.028099174\n",
" },\n",
" {\n",
" \"confidenceThreshold\": 0.05,\n",
" \"recall\": 1.0,\n",
" \"precision\": 0.5862069,\n",
" \"f1Score\": 0.73913044\n",
" },\n",
" {\n",
" \"confidenceThreshold\": 0.94,\n",
" \"recall\": 0.64705884,\n",
" \"precision\": 1.0,\n",
" \"f1Score\": 0.7857143\n",
" },\n",
" \n",
" # REMOVED FOR BREVITY\n",
" \n",
" {\n",
" \"confidenceThreshold\": 0.999,\n",
" \"recall\": 0.21372032,\n",
" \"precision\": 1.0,\n",
" \"f1Score\": 0.35217392\n",
" },\n",
" {\n",
" \"confidenceThreshold\": 1.0,\n",
" \"recall\": 0.0026385225,\n",
" \"precision\": 1.0,\n",
" \"f1Score\": 0.005263158\n",
" }\n",
" ],\n",
" \"logLoss\": 0.14686257\n",
" },\n",
" \"displayName\": \"achievement\"\n",
" }\n",
"]\n",
"```\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "i6T0bzuNJjkY"
},
"source": [
"### [projects.locations.models.modelEvaluations.get](https://cloud.google.com/automl/docs/reference/rest/v1beta1/projects.locations.models.modelEvaluations/get)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "16ZPQWjulH6_"
},
"source": [
"#### Call"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "aorkRa76lH7A"
},
"outputs": [],
"source": [
"request = clients[\"automl\"].get_model_evaluation(name=evaluation_slice)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "pHodXIWxlH7A"
},
"source": [
"#### Response"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "CX5GXZkDlH7A"
},
"outputs": [],
"source": [
"print(MessageToJson(request.__dict__[\"_pb\"]))"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "XauXDBQfaGwx"
},
"source": [
"*Example output*:\n",
"```\n",
"{\n",
" \"name\": \"projects/116273516712/locations/us-central1/models/TCN5333697920992542720/modelEvaluations/1436745357261371663\",\n",
" \"annotationSpecId\": \"3130761503557287936\",\n",
" \"createTime\": \"2021-03-01T02:56:28.878044Z\",\n",
" \"evaluatedExampleCount\": 1193,\n",
" \"classificationEvaluationMetrics\": {\n",
" \"auPrc\": 0.99065405,\n",
" \"confidenceMetricsEntry\": [\n",
" {\n",
" \"recall\": 1.0,\n",
" \"precision\": 0.01424979,\n",
" \"f1Score\": 0.028099174\n",
" },\n",
" {\n",
" \"confidenceThreshold\": 0.05,\n",
" \"recall\": 1.0,\n",
" \"precision\": 0.5862069,\n",
" \"f1Score\": 0.73913044\n",
" },\n",
" \n",
" # REMOVED FOR BREVITY\n",
" \n",
" {\n",
" \"confidenceThreshold\": 0.999,\n",
" \"recall\": 0.23529412,\n",
" \"precision\": 1.0,\n",
" \"f1Score\": 0.3809524\n",
" },\n",
" {\n",
" \"confidenceThreshold\": 1.0,\n",
" \"precision\": 1.0\n",
" }\n",
" ],\n",
" \"logLoss\": 0.005436425\n",
" },\n",
" \"displayName\": \"exercise\"\n",
"}\n",
"```\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "xksNVRJIlH7A"
},
"source": [
"## Make batch predictions"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "CilSsXsyaGw5"
},
"source": [
"### Prepare files for batch prediction"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "6uSIK0_jaGw5"
},
"outputs": [],
"source": [
"test_item = ! gsutil cat $IMPORT_FILE | head -n1\n",
"test_item, test_label = str(test_item[0]).split(\",\")\n",
"\n",
"print(test_item, test_label)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "4Saj5dsWlH7A"
},
"outputs": [],
"source": [
"import json\n",
"\n",
"import tensorflow as tf\n",
"\n",
"test_item_uri = \"gs://\" + BUCKET_NAME + \"/test.txt\"\n",
"with tf.io.gfile.GFile(test_item_uri, \"w\") as f:\n",
" f.write(test_item + \"\\n\")\n",
"\n",
"gcs_input_uri = \"gs://\" + BUCKET_NAME + \"/batch.csv\"\n",
"with tf.io.gfile.GFile(gcs_input_uri, \"w\") as f:\n",
" f.write(test_item_uri + \"\\n\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "nTTzKkr7aGw6"
},
"outputs": [],
"source": [
"! gsutil cat $gcs_input_uri\n",
"! gsutil cat $test_item_uri"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "TPtwEmoeaGw6"
},
"source": [
"*Example output*:\n",
"```\n",
"gs://migration-ucaip-trainingaip-20210228224317/test.txt\n",
"I went on a successful date with someone I felt sympathy and connection with.\n",
"```\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "text_models_batchpredict:migration,old"
},
"source": [
"### [projects.locations.models.batchPredict](https://cloud.google.com/automl/docs/reference/rest/v1beta1/projects.locations.models/batchPredict)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "9Vyk6FVxlH7C"
},
"source": [
"#### Request"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "C73-3tt0lH7C"
},
"outputs": [],
"source": [
"input_config = {\"gcs_source\": {\"input_uris\": [gcs_input_uri]}}\n",
"\n",
"output_config = {\n",
" \"gcs_destination\": {\"output_uri_prefix\": \"gs://\" + f\"{BUCKET_NAME}/batch_output/\"}\n",
"}\n",
"\n",
"print(\n",
" MessageToJson(\n",
" automl.BatchPredictRequest(\n",
" name=model_id, input_config=input_config, output_config=output_config\n",
" ).__dict__[\"_pb\"]\n",
" )\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "TX0IQkdOaGw8"
},
"source": [
"*Example output*:\n",
"```\n",
"{\n",
" \"name\": \"projects/116273516712/locations/us-central1/models/TCN5333697920992542720\",\n",
" \"inputConfig\": {\n",
" \"gcsSource\": {\n",
" \"inputUris\": [\n",
" \"gs://migration-ucaip-trainingaip-20210228224317/batch.csv\"\n",
" ]\n",
" }\n",
" },\n",
" \"outputConfig\": {\n",
" \"gcsDestination\": {\n",
" \"outputUriPrefix\": \"gs://migration-ucaip-trainingaip-20210228224317/batch_output/\"\n",
" }\n",
" }\n",
"}\n",
"```\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "D5pvxloAlH7C"
},
"source": [
"#### Call"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "VMiC645dlH7C"
},
"outputs": [],
"source": [
"request = clients[\"prediction\"].batch_predict(\n",
" name=model_id, input_config=input_config, output_config=output_config\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "kFtsjWHIlH7D"
},
"source": [
"#### Response"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "Nqg__59clH7D"
},
"outputs": [],
"source": [
"result = request.result()\n",
"\n",
"print(MessageToJson(result.__dict__[\"_pb\"]))"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "771dDuKzg8Mk"
},
"source": [
"*Example output*:\r\n",
"```\r\n",
"{}\r\n",
"```"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "fnYRCde3xXie"
},
"outputs": [],
"source": [
"destination_uri = output_config[\"gcs_destination\"][\"output_uri_prefix\"][:-1]\n",
"\n",
"! gsutil ls $destination_uri/*\n",
"! gsutil cat $destination_uri/prediction*/*.jsonl"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "gVNVzw5EaGw-"
},
"source": [
"*Example output*:\n",
"```\n",
"gs://migration-ucaip-trainingaip-20210228224317/batch_output/prediction-happiness_20210228224317-2021-03-01T02:57:02.004934Z/text_classification_1.jsonl\n",
"gs://migration-ucaip-trainingaip-20210228224317/batch_output/prediction-happiness_20210228224317-2021-03-01T02:57:02.004934Z/text_classification_2.jsonl\n",
"{\"textSnippet\":{\"contentUri\":\"gs://migration-ucaip-trainingaip-20210228224317/test.txt\"},\"annotations\":[{\"annotationSpecId\":\"5436604512770981888\",\"classification\":{\"score\":0.93047273},\"displayName\":\"affection\"},{\"annotationSpecId\":\"3707222255860711424\",\"classification\":{\"score\":0.002518793},\"displayName\":\"achievement\"},{\"annotationSpecId\":\"7742447521984675840\",\"classification\":{\"score\":1.3182563E-4},\"displayName\":\"enjoy_the_moment\"},{\"annotationSpecId\":\"824918494343593984\",\"classification\":{\"score\":0.06613126},\"displayName\":\"bonding\"},{\"annotationSpecId\":\"1977839998950440960\",\"classification\":{\"score\":1.5267624E-5},\"displayName\":\"leisure\"},{\"annotationSpecId\":\"8318908274288099328\",\"classification\":{\"score\":8.887557E-6},\"displayName\":\"nature\"},{\"annotationSpecId\":\"3130761503557287936\",\"classification\":{\"score\":7.2130124E-4},\"displayName\":\"exercise\"}]}\n",
"```"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "y_rNqE85lH7D"
},
"source": [
"## Make online predictions"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "text_models_deploy:migration,old"
},
"source": [
"### [projects.locations.models.deploy](https://cloud.google.com/automl/docs/reference/rest/v1beta1/projects.locations.models/deploy)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "VUfhwbkLlH7E"
},
"source": [
"#### Call"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "tojYy4j6lH7E"
},
"outputs": [],
"source": [
"request = clients[\"automl\"].deploy_model(name=model_id)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "8OaGY7JmlH7E"
},
"source": [
"#### Response"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "voC8sroOlH7E"
},
"outputs": [],
"source": [
"result = request.result()\n",
"\n",
"print(MessageToJson(result))"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "CZ-62obNmBNc"
},
"source": [
"*Example output*:\r\n",
"```\r\n",
"{}\r\n",
"```"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "text_models_predict:migration,old"
},
"source": [
"### [projects.locations.models.predict](https://cloud.google.com/automl/docs/reference/rest/v1beta1/projects.locations.models/predict)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "v3Hc1PEyyabD"
},
"source": [
"### Prepare data item for online prediction"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "EzXouIJ0aGxB"
},
"outputs": [],
"source": [
"test_item = ! gsutil cat $IMPORT_FILE | head -n1\n",
"test_item, test_label = str(test_item[0]).split(\",\")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "LcSHb_A0lH7F"
},
"source": [
"#### Request"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "BEHtyu-BlH7F"
},
"outputs": [],
"source": [
"payload = {\"text_snippet\": {\"content\": test_item, \"mime_type\": \"text/plain\"}}\n",
"\n",
"request = automl.PredictRequest(name=model_id, payload=payload)\n",
"\n",
"print(MessageToJson(request.__dict__[\"_pb\"]))"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "In8qh2Z1aGxC"
},
"source": [
"*Example output*:\n",
"```\n",
"{\n",
" \"name\": \"projects/116273516712/locations/us-central1/models/TCN5333697920992542720\",\n",
" \"payload\": {\n",
" \"textSnippet\": {\n",
" \"content\": \"I went on a successful date with someone I felt sympathy and connection with.\",\n",
" \"mimeType\": \"text/plain\"\n",
" }\n",
" }\n",
"}\n",
"```\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "xR4xdzeflH7F"
},
"source": [
"#### Call"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "Cfy8J23SlH7F"
},
"outputs": [],
"source": [
"request = clients[\"prediction\"].predict(request=request)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "N0dT5DXblH7F"
},
"source": [
"#### Response"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "CHf-Y_XtlH7G"
},
"outputs": [],
"source": [
"print(MessageToJson(request.__dict__[\"_pb\"]))"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "3RxSK0xDaGxC"
},
"source": [
"*Example output*:\n",
"```\n",
"{\n",
" \"payload\": [\n",
" {\n",
" \"annotationSpecId\": \"5436604512770981888\",\n",
" \"classification\": {\n",
" \"score\": 0.9272586\n",
" },\n",
" \"displayName\": \"affection\"\n",
" },\n",
" {\n",
" \"annotationSpecId\": \"824918494343593984\",\n",
" \"classification\": {\n",
" \"score\": 0.068884976\n",
" },\n",
" \"displayName\": \"bonding\"\n",
" },\n",
" {\n",
" \"annotationSpecId\": \"3707222255860711424\",\n",
" \"classification\": {\n",
" \"score\": 0.0028119811\n",
" },\n",
" \"displayName\": \"achievement\"\n",
" },\n",
" {\n",
" \"annotationSpecId\": \"3130761503557287936\",\n",
" \"classification\": {\n",
" \"score\": 0.0008869726\n",
" },\n",
" \"displayName\": \"exercise\"\n",
" },\n",
" {\n",
" \"annotationSpecId\": \"7742447521984675840\",\n",
" \"classification\": {\n",
" \"score\": 0.00013229548\n",
" },\n",
" \"displayName\": \"enjoy_the_moment\"\n",
" },\n",
" {\n",
" \"annotationSpecId\": \"1977839998950440960\",\n",
" \"classification\": {\n",
" \"score\": 1.5584701e-05\n",
" },\n",
" \"displayName\": \"leisure\"\n",
" },\n",
" {\n",
" \"annotationSpecId\": \"8318908274288099328\",\n",
" \"classification\": {\n",
" \"score\": 9.5975e-06\n",
" },\n",
" \"displayName\": \"nature\"\n",
" }\n",
" ]\n",
"}\n",
"```\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "bQ-VVaSxJjkd"
},
"source": [
"# Cleaning up\r\n",
"\r\n",
"To clean up all GCP resources used in this project, you can [delete the GCP\r\n",
"project](https://cloud.google.com/resource-manager/docs/creating-managing-projects#shutting_down_projects) you used for the tutorial.\r\n",
"\r\n",
"Otherwise, you can delete the individual resources you created in this tutorial."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "pTymPfKolH7G"
},
"outputs": [],
"source": [
"delete_dataset = True\n",
"delete_model = True\n",
"delete_bucket = True\n",
"\n",
"# Delete the dataset using the AutoML fully qualified identifier for the dataset\n",
"try:\n",
" if delete_dataset:\n",
" clients[\"automl\"].delete_dataset(name=dataset_id)\n",
"except Exception as e:\n",
" print(e)\n",
"\n",
"# Delete the model using the AutoML fully qualified identifier for the model\n",
"try:\n",
" if delete_model:\n",
" clients[\"automl\"].delete_model(name=model_id)\n",
"except Exception as e:\n",
" print(e)\n",
"\n",
"\n",
"if delete_bucket and \"BUCKET_NAME\" in globals():\n",
" ! gsutil rm -r gs://$BUCKET_NAME"
]
}
],
"metadata": {
"colab": {
"collapsed_sections": [
"J_croPBoJjkK",
"h_L3MRsOmYED",
"MDUAZaN3JjkL",
"fR9geV9pJjkO",
"hIHTX-pkJjkO",
"lbv411XjJjkP",
"vHkuSZxkJjkT",
"FLqkZMD2JjkT",
"text_datasets_importdata:migration,old",
"VkfdNI66lH66",
"Gmg3fbX_lH66",
"WMUN_7EclH67",
"text_models_create:migration,old",
"sbJ0wIRHlH67",
"K2UcVNlAlH68",
"rTFtnIKZlH6-",
"yfufMwAEJjkX",
"4wJgA2D8lH6_",
"IBOLi2gflH6_",
"i6T0bzuNJjkY",
"16ZPQWjulH6_",
"pHodXIWxlH7A",
"CilSsXsyaGw5",
"text_models_batchpredict:migration,old",
"9Vyk6FVxlH7C",
"D5pvxloAlH7C",
"kFtsjWHIlH7D",
"text_models_deploy:migration,old",
"VUfhwbkLlH7E",
"8OaGY7JmlH7E",
"text_models_predict:migration,old",
"v3Hc1PEyyabD",
"LcSHb_A0lH7F",
"xR4xdzeflH7F",
"N0dT5DXblH7F"
],
"name": "UJ6 legacy AutoML Natural Language Text Classification.ipynb",
"toc_visible": true
},
"kernelspec": {
"display_name": "Python 3",
"name": "python3"
}
},
"nbformat": 4,
"nbformat_minor": 0
}